package com.qkjia.mvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * Date:2021/9/6
 * author:zhaoqiankun
 * Description: 使用ServletAPI向request域对象共享数据
 *
 * Model、ModelMap、Map的关系
 * Model、ModelMap、Map类型的参数其实本质上都是 BindingAwareModelMap 类型的
 *
 * 結果是点击了页面 有数据
 */
@Controller
public class ScopeController {


    /**
     * 使用servletAPI向request域对象共享数据
     * @param request 当前请求
     * @return success视图
     */
    @RequestMapping("/testRequestByServletAPI")
    public String testRequestByServletAPI(HttpServletRequest request){
        request.setAttribute("testRequestScope", "hello,servletAPI");
        return "success";
    }

    /**
     *  使用ModelAndView向request域对象共享数据
     * @return success
     */
    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView(){
        /*** ModelAndView有Model和View的功能
         * Model主要用于向请求域共享数据 * View主要用于设置视图，实现页面跳转
         */
        ModelAndView mav = new ModelAndView();
        //处理模型数据，即向请求域request共享数据
        mav.addObject("testRequestScope", "hello,ModelAndView");
        //设置视图名称，实现页面跳转
        mav.setViewName("success");
        return mav;
    }


    /**
     * 使用Model向request域对象共享数据
     * @param model Model
     * @return success
     */
    @RequestMapping("/testModel")
    public String testModel(Model model){
        model.addAttribute("testRequestScope", "hello,model");
        System.out.println(model.getClass().getName());
        return "success";
    }

    /**
     * 使用map向request域对象共享数据
     * @param map
     * @return  success
     */
    @RequestMapping("/testMap")
    public String testMap(Map<String, Object> map){
        map.put("testRequestScope", "hello,map");
        System.out.println(map.getClass().getName());
        return "success";
    }

    /**
     * 使用ModelMap向request域对象共享数据
     * @param modelMap modelMap
     * @return  success
     */
    @RequestMapping("/testModelMap")
    public String testModelMap(ModelMap modelMap){
        modelMap.addAttribute("testRequestScope", "hello,ModelMap");
        System.out.println(modelMap.getClass().getName());
        return "success";
    }

    @RequestMapping("/testSession")
    public String testSession(HttpSession session){
        session.setAttribute("testSessionScope", "hello,session");
        return "success";
    }

    @RequestMapping("/testApplication")
    public String testApplication(HttpSession session){
        ServletContext application = session.getServletContext();
        application.setAttribute("testApplicationScope", "hello,application");
        return "success";
    }

}
